package de.hub.sar.itsec.sslfetcher.utils;

import java.util.concurrent.TimeUnit;

public final class Converter {
	private Converter() {
	}

	private static final String HEXES = "0123456789ABCDEF";

	public static byte[] getByteArray(int size, long value) {
		byte[] result;

		result = new byte[size];
		for (size--; size > -1; size--) {
			result[size] = (byte) (value & 0xff);
			value >>= Byte.SIZE;
		}

		return result;
	}

	public static int getInt(byte[] bytes) {
		int result;

		result = 0;
		for (int i = 0; i < bytes.length; i++) {
			result <<= Byte.SIZE;
			result += bytes[i] & 0xff;
		}

		return result;
	}

	public static String getHexString(byte[] bytes, char delimiter) {
		final StringBuilder sb = new StringBuilder(2 * bytes.length);

		for (final byte b : bytes) {
			sb.append(HEXES.charAt((b & 0xF0) >> 4)).append(
					HEXES.charAt((b & 0x0F)));
			sb.append(delimiter);
		}

		return sb.toString();
	}

	public static String hostToFolderName(final String host) {
		return host.replaceAll("\\|/", host);
	}

	public static String millisToString(long millis) {
		StringBuilder sb;
		long days;
		long hours;
		long minutes;
		long seconds;
		
		sb = new StringBuilder(100);
		
		if (millis < 0) {
			return sb.toString();
		} else if (millis == 0) {
			return "< 0 Milliseconds";
		}

		days = TimeUnit.MILLISECONDS.toDays(millis);
		millis -= TimeUnit.DAYS.toMillis(days);
		hours = TimeUnit.MILLISECONDS.toHours(millis);
		millis -= TimeUnit.HOURS.toMillis(hours);
		minutes = TimeUnit.MILLISECONDS.toMinutes(millis);
		millis -= TimeUnit.MINUTES.toMillis(minutes);
		seconds = TimeUnit.MILLISECONDS.toSeconds(millis);
		millis -= TimeUnit.SECONDS.toMillis(seconds);
		
		if (days > 0) {
			sb.append(days);
			sb.append("d ");
		}
		if (hours > 0) {
			sb.append(hours);
			sb.append("h ");
		}
		if (minutes > 0) {
			sb.append(minutes);
			sb.append("m ");
		}
		if (seconds > 0) {
			sb.append(seconds);
			sb.append("s ");
		}
		if (millis > 0) {
			sb.append(millis);
			sb.append("ms");
		}

		return (sb.toString());
	}

}
